package com.zyz.O_网络编程.TCP.single;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: vick
 * @Date: 2025/4/15
 * @Description:
 * @version: 1.0
 */
public class Server {
    public static void main(String[] args) throws IOException {
        //System.out.println(InetAddress.getLocalHost());//127.0.0.1 或者 192.168.0.106
        //1. 创建ServerSocket对象，绑定8888端口
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("====服务端===");
        System.out.println("===服务端已启动，等待接收客户端请求===");
        //2. 监听客户端的连接， 这个方法是阻塞的，如果没有客户端连接会一致等待
        Socket socket = serverSocket.accept();
        InetAddress inetAddress = socket.getInetAddress();
        System.out.println(inetAddress.getHostAddress() + "客户端连接成功");

        //3. 获取输入流，接收客户端发送过来的数据
        InputStream inputStream = socket.getInputStream();

        //定义字节数组
        byte[] data = new byte[1024];
        StringBuilder str = new StringBuilder();
        int len;
        //循环读取
        while ((len = inputStream.read(data)) != -1) {
            str.append(new String(data, 0, len));
        }
        System.out.println(inetAddress.getHostAddress() + "客户端发送的消息是：" + str);

        //4. 获取输出流，发送数据给客户端
        OutputStream outputStream = socket.getOutputStream();
        //发送数据
        outputStream.write("welcome".getBytes());
        outputStream.flush();

        //5. 关闭socket，不再与客户端通信
        socket.close();
        serverSocket.close();
    }
}
